$(document).ready(function ($) {
    $('.more_button').on('click', function (e) {
        let target = $(e.target);
        let data = get_page_data(target);

        toggleBlockForm(target, 24);

        $.ajax({
            url: window.location,
            type: 'POST',
            async: true,
            data: data,
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false
        })
            .done(function (result) {
                if(result.status === 'ok') {
                    toggleBlockForm(target);
                    let new_page = $('<div></div>').append(result.html);
                    $(document).trigger('siriuso_pagination', new_page);
                    new_page.insertBefore(target);
                    //alert(target.parent().find('.komunumoj_socio_listo').length);

                    if(!result.more) {
                        target.remove();
                    } else if(typeof result.offset !== 'undefined') {
                        target.attr('data-page-offset', result.offset);
                    }

                    if(typeof result.multi !== 'undefined' && typeof page_multi !== 'undefined') {
                        $.each(JSON.parse(result.multi), function (idx, val) {
                            page_multi[idx] = val;
                        });
                    }
                } else {
                    console.log("Bad server response: " + result.err);
                    toggleBlockForm(target);
                }
            })
            .fail(function (jqXHR, textStatus) {
                target.remove();
                console.log("Request failed: " + textStatus);
            });
    });

    function get_page_data(target) {
        let data = new FormData();

        $.each(target[0].attributes, function () {
            if(this.specified && /^data-page-/.test(this.name)) {
                data.append(this.name.replace(/^data-page-/, ''), this.value);
            }
        });

        if(typeof page_multi !== 'undefined' && data.has('typo') && data.get('typo') === 'multi') {
            data.append('page_multi', JSON.stringify(page_multi))
        }

        if(!data.has('page') && !data.has('offset')) {
            data.append('page', 1);
        }

        data.append('csrfmiddlewaretoken', getCookie('csrftoken'));

        return data;
    }
});
